import { AfterViewInit, Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Graph } from '@antv/x6';
import { AlgoGraphProcessService } from '../algo-graph-process.service';
import { AlgoUnitMetadata } from '../algo-unit-metadata';
import { AlgoUnitService } from '../algo-unit.service';
import { FlowGraphDesignService } from '../flow-graph-design.service';
import { AlgoUnitSettingSidebarComponent } from './algo-unit-setting-sidebar/algo-unit-setting-sidebar.component';

@Component({
  selector: 'app-flow-graph-design',
  templateUrl: './flow-graph-design.component.html',
  styleUrl: './flow-graph-design.component.scss'
})
export class FlowGraphDesignComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild("graphContainer", { static: true })
  graphContainer!: ElementRef;
  @ViewChild("dndContainer", { static: true })
  dndContainer!: ElementRef;
  graph!: Graph;

  @ViewChild("settingSidebar", { static: true })
  settingSidebar!: AlgoUnitSettingSidebarComponent;

  types: AlgoUnitMetadata[] = [];

  constructor(private service: FlowGraphDesignService,
    private algoService: AlgoUnitService,
    private processService: AlgoGraphProcessService) { }

  ngOnInit(): void {
    this.service.nodeDblclick.subscribe((cfg) => this._onNodeDblClick(cfg));
  }
  private _onNodeDblClick(cfg: AlgoUnitMetadata): void {
    console.log(cfg);
    this.settingSidebar.onEdit(cfg);

  }
  onHideSettingSidebar(cfg: AlgoUnitMetadata) {

  }

  ngAfterViewInit(): void {
    this.service.registerGraphTypes();
    this.service.initGraph(this.graphContainer.nativeElement, this.dndContainer.nativeElement);

    this.algoService.getList().subscribe(res => {
      this.types = res.map(a => ({ ...a, Name: `${a.Name} ${a.In.length}:${a.Out.length}` }));
      this.service.initStencil(this.types);
    });

    this.AddNodes();
  }

  AddNodes() {

  }

  ngOnDestroy(): void {
    this.service.unregisterGraphTypes();
  }

  startDrag(e: MouseEvent, item: AlgoUnitMetadata) {
    this.service.startDrag(e, item);
  }

  onSaveJson() {
    this.service.saveToJson();
  }
  onLoadJson() {
    this.service.loadFromJson();
  }
  onGetAlgoGraph() {
    const flowGraph = this.service.getAlgoGraph();
    console.log(flowGraph);


    localStorage.setItem("flowGraph", JSON.stringify(flowGraph));
  }
  onLoadAlgoGraph() {
    const flowGraph = JSON.parse(localStorage.getItem("flowGraph") || "{}");
    this.service.loadAlgoGraph(flowGraph);
  }

  onExecute() {
    const cfg = this.service.getAlgoGraph();
    this.processService.execute(cfg);
  }
}
